package com.whater.wechat.service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.whater.common.domain.AjaxResult;
import com.whater.common.util.StringUtils;
import com.whater.wechat.dao.VideosDao;
import com.whater.wechat.entity.Videos;
import com.whater.wechat.util.CommonUtil;
import com.whater.wechat.vo.PathVo;
import com.whater.wechat.vo.VideoVo;

@Service
public class VideoService {

	@Value("${wechat.video.path}")
	private String videoPath;
	@Value("${wechat.backup.path}")
	private String backupPath;
	@Autowired
	private VideosDao videosDao;

	public List<PathVo> getPath(String path) {
		String realPath = videoPath;
		if (StringUtils.isNotEmpty(path)) {
			realPath += "/" + path;
		}
		return Arrays.asList(new File(realPath).listFiles()).stream().map(item -> {
			return new PathVo(item.getAbsolutePath(), item.getName(), isDate(item.getName()));
		}).collect(Collectors.toList());
	}

	public AjaxResult getImage(String path, Integer skip, Integer limit, final boolean includeOptData,
			boolean selectedData) {
		String realPath = videoPath;
		if (StringUtils.isNotEmpty(path)) {
			realPath += "/" + path;
		}
		Videos imagesExample = new Videos();
		imagesExample.setSelected(true);
		Set<String> set = videosDao.findAll(Example.of(imagesExample)).parallelStream().map(Videos::getShortName)
				.collect(Collectors.toSet());
		Set<String> allOptDate = new HashSet<>();
		if (!includeOptData) {
			allOptDate = videosDao.findAll().parallelStream().map(Videos::getShortName).collect(Collectors.toSet());
		}
		final Set<String> allOptDateEnd = allOptDate;
		final AtomicInteger atomicInteger = new AtomicInteger(0);
		File file = new File(realPath) ;
		AjaxResult result = AjaxResult.success(Arrays.asList(file.listFiles()).stream()
				.filter(e->{
					return "mp4".equals(e.getName().split("\\.")[1]);
				})
				.filter(e -> {
					if (selectedData) {
						return set.contains(e.getName());
					}
					if (!includeOptData)
						atomicInteger.incrementAndGet();
					return includeOptData || !allOptDateEnd.contains(e.getName());
				}).skip(skip).limit(limit)
				.map(item -> {
					return new VideoVo(item.getName(), item.lastModified(), set.contains(item.getName()),item.getName().split("\\.")[1]);
				}).collect(Collectors.toList()));
		result.put("resultSkip", skip + atomicInteger.get());
		result.put("total", Arrays.asList(file.listFiles()).stream()
				.filter(e->{
					return "mp4".equals(e.getName().split("\\.")[1]);
				})
				.skip(skip).limit(limit).collect(Collectors.toList()).size());
		return result;
	}

	public String getFullPath(String image) {
		String realPath = videoPath;
		if (StringUtils.isNotEmpty(image)) {
			realPath += "/" + image;
		}
		return realPath;
	}

	public boolean isDate(String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd");
			sdf.parse(date);
		} catch (ParseException e) {
			return false;
		}
		return true;
	}

	@Transactional
	public AjaxResult submit(JSONArray data) {
		data.forEach(item -> {
			Map<?, ?> jsonObject = (Map<?, ?>) item;
			Videos video = videosDao.findByShortName(jsonObject.get("id").toString());
			if (video == null) {
				video = new Videos();
			}
			video.setCrtDate(new Date((Long) jsonObject.get("crtDate")));
			video.setShortName(jsonObject.get("id").toString());
			video.setPath(jsonObject.get("dir").toString());
			video.setFullPath(jsonObject.get("dir").toString() + "/" + jsonObject.get("id").toString());
			video.setSelected((Boolean) jsonObject.get("selected"));
			video.setFileType(jsonObject.get("id").toString().split("\\.")[1]);
			videosDao.save(video);
		});
		return AjaxResult.success();
	}

	@Transactional
	public AjaxResult export(JSONArray data) {
		data.forEach(item -> {
			Map<?, ?> jsonObject = (Map<?, ?>) item;
			Videos video = videosDao.findByShortName(jsonObject.get("id").toString());
			if (video == null) {
				video = new Videos();
			}
			if(video.getExported() !=null && video.getExported()) {
				return;
			}
			video.setCrtDate(new Date((Long) jsonObject.get("crtDate")));
			video.setShortName(jsonObject.get("id").toString());
			video.setPath(jsonObject.get("dir").toString());
			video.setFullPath(jsonObject.get("dir").toString() + "/" + jsonObject.get("id").toString());
			video.setSelected((Boolean) jsonObject.get("selected"));
			video.setFileType(jsonObject.get("id").toString().split("\\.")[1]);
			File file = new File(backupPath+"/video/"+video.getFullPath());
			file.getParentFile().mkdirs();
			try {
				CommonUtil.doCopyFile(new File(getFullPath(video.getFullPath())), file);
			} catch (IOException e) {
				e.printStackTrace();
				return ;
			}
			video.setExported(true);
			videosDao.save(video);
		});
		return AjaxResult.success();
	}
}
